package org.ssp.service;

import java.net.InetAddress;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.junit.Test;
import org.ssp.pojo.Order;
import org.ssp.util.CommonUtil;
import org.ssp.util.MD5Util;
import org.ssp.util.XML2Obj2XML;

/**
 * WXPay Service 
 * @author susp
 *
 */
public class WXPayService {
	public static final String  UNIFIEDORDER="https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单api
	public static final String KEY="1i2ujh3y7di99ianmjwoodlwmm4ijsio";//商户api key
	public static final String MCH_ID ="1369118002";//商户id
    public static final String NOTIFY_URL=CoreService.BaseUrl+"/oec/notifyhandle";

    public static void main(String[] args) {
		SortedMap<Object,Object> paramaters=new TreeMap<Object,Object>();
		paramaters.put("appId","wx33b73bd6220f28a4");
		paramaters.put("nonceStr","5EQd6yftw8yx4FNH" );
		paramaters.put("package","prepay_id=wx20160915111030d64285351f0483207207");
		paramaters.put("signType", "MD5");
		paramaters.put("timeStamp", "1473909030");
		String sign=WXPayService.createSign("utf-8", paramaters);
		System.out.println(sign);
	}
    
    /**
     * 统一下单请求
     * 
     * @param json
     * @param access_token
     * @return
     */
	public static String getOrderMap(String json){
		System.out.println("enter...getOrderMap...");
		String result=null;//修改为null
		try {
			result=CommonUtil.httpsRequest(UNIFIEDORDER, "POST", json);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 生成签名
	 * 
	 * @param characterEncoding
	 * @param paramaters
	 * @return
	 */
	 public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters){  
	        StringBuffer sb = new StringBuffer();  
	        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
	        Iterator it = es.iterator();  
	        while(it.hasNext()) {  
	            Map.Entry entry = (Map.Entry)it.next();  
	            String k = (String)entry.getKey();  
	            Object v = entry.getValue();  
	            if(null != v && !"".equals(v)   
	                    && !"sign".equals(k) && !"key".equals(k)) {  
	                sb.append(k + "=" + v + "&");  
	            }  
	        }  
	        sb.append("key=" + WXPayService.KEY);  
	        String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
	        return sign;  
	    }  
	/**
	 * 生成随机字符串
	 * @return
	 */
	public static String CreateNoncestr() {
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String res = "";
		for (int i = 0; i < 16; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}
	
	/**
	 * 生成随机字符串
	 * @return
	 */
	public static String CreatePno() {
		String chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		String res = "";
		for (int i = 0; i < 16; i++) {
			Random rd = new Random();
			res += chars.charAt(rd.nextInt(chars.length() - 1));
		}
		return res;
	}
	@Test
	public void createpno_test(){
		System.out.println(CreatePno());
	}
	/**
	 * 获取unix时间，从1970-01-01 00:00:00开始的秒数
	 * @param date
	 * @return long
	 */
	public static String getUnixTime(Date date) {
		if( null == date ) {
			return "";
		}
		return String.valueOf(date.getTime()/1000);
	}
	@Test
	public void test(){
		System.out.println(getUnixTime(new Date()));
		
	}
	@Test
	public void test2(){
		String price="0.02";
		System.out.println(String.valueOf(Double.valueOf(price)*100));
		
	}
	/**
	 * 验证签名
	 * @param map
	 * @return
	 */
	public static boolean verifyWeixinNotify(Map<String, String> map) {  
        SortedMap<Object, Object> parameterMap = new TreeMap<Object, Object>();  
        String sign = (String) map.get("sign");  
        for (Object keyValue : map.keySet()) {  
            if(!keyValue.toString().equals("sign")){  
                parameterMap.put(keyValue.toString(), map.get(keyValue));  
            }  
              
        }  
        String createSign =createSign("UTF-8", parameterMap);  
        if(createSign.equals(sign)){  
            return true;  
        }else{  
            return false;  
        }  
    }  
	
	@Test
	public void test12(){
		Map<String,Object> map=new TreeMap<String,Object>();
		map.put("time_end", "20141030133525");
		map.put("out_trade_no","shish3980xhjo098");
		map.put("attch","测试");
		map.put("openid", "sjo_ahroo10jojosjo");
		map.put("total_fee", "1");
		Order order=new Order();
		order.setOrderId(String.valueOf(map.get("out_trade_no")));
		order.setName(String.valueOf(map.get("attach")));
		order.setPaytime(String.valueOf(map.get("time_end")));
		order.setOpenid(String.valueOf(map.get("openid")));
		order.setStatus(1);
		order.setTotal_fee(Integer.valueOf(map.get("total_fee").toString()));
        System.out.println(order.getPaytime());
	}
}
